<template>
  <div class="project">
    <div
      class="left"
      :key="this.fundBuildSource + this.landingMethod"
    >
      <div
        class="form"
        v-for="(item, index) in templateInfo"
        :key="index"
      >
        <div class="title" v-if="item.showType">
          {{ item.nodeType }}
        </div>

        <div class="item-title">
          <el-checkbox
            true-label="1"
            false-label="0"
            v-model="item.selected"
            :disabled="
              !canCheck(item, index, templateInfo) ||
              isDetail
            "
            @change="handleCheckboxChange(item, index)"
          ></el-checkbox>
          <div
            class="name"
            :class="{
              active: !canCheck(item, index, templateInfo)
            }"
          >
            {{ item.nodeName }}
            <b v-if="item.hasMain == '1'">(关键节点)</b>
            <span v-if="item.createTime">
              转入时间：{{ item.createTime }}
            </span>
          </div>
        </div>
        <!-- <template v-if="index !== 0"> -->
        <template>
          <div
            class="content"
            v-show="
              shouldShowContent(item, index, templateInfo)
            "
          >
            <el-row>
              <el-col :span="6">
                <p class="item-tit">办理情况</p>
                <el-radio-group
                  class="item-radio-group"
                  v-model="item.nodeStatus"
                  @change="
                    (value) =>
                      onChangeNodeStatus(value, item, index)
                  "
                  :disabled="
                    !canStatusChange(
                      item,
                      index,
                      templateInfo
                    ) || isDetail
                  "
                >
                  <el-radio label="办理中">办理中</el-radio>
                  <el-radio label="已办结">已办结</el-radio>
                  <el-radio
                    v-if="item.hasTolerance == '1'"
                    label="容缺补办"
                    >容缺补办</el-radio
                  >
                  <el-radio label="无需办理"
                    >无需办理</el-radio
                  >
                  <el-radio
                    v-if="
                      item.processNodeId == '1-9' ||
                      item.pkid == '1-9'
                    "
                    label="提前交地"
                    >提前交地
                  </el-radio>
                </el-radio-group>
              </el-col>
              <el-col :span="9">
                <p class="item-tit">当前卡点</p>
                <el-input
                  style="width: 100%"
                  type="textarea"
                  class="resize-textarea"
                  v-model="item.nodeRemarks"
                  placeholder="请输入"
                  :disabled="isDetail"
                ></el-input>
              </el-col>
              <el-col
                :span="9"
                v-show="
                  ['提前交地', '已办结'].includes(
                    item.nodeStatus
                  )
                "
              >
                <p class="item-tit">
                  <span
                    v-if="!notRequiredNodeFinishTime(item)"
                    style="color: #f56c6c"
                    >*</span
                  >
                  实际完成时间
                </p>
                <el-date-picker
                  style="width: 100%"
                  v-model="item.nodeFinishTime"
                  type="date"
                  placeholder="年/月/日"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                  :disabled="isDetail"
                >
                </el-date-picker>
              </el-col>
            </el-row>
          </div>
        </template>
      </div>
    </div>
    <div class="right">
      <div class="project-part-title">建设要素保障</div>
      <div
        class="form"
        v-for="(item, index) in elementInfo"
        :key="index"
      >
        <div class="item-title">
          <el-checkbox
            true-label="1"
            false-label="0"
            v-model="item.selected"
            :disabled="isDetail"
            @change="onChangeCheckboxElement(item, index)"
          ></el-checkbox>
          <div class="name">
            {{ item.dictText }}
          </div>
        </div>
        <div class="content" v-show="item.selected == '1'">
          <div class="item-row">
            <span class="item-row-title">办理情况</span>
            <el-radio-group
              v-model="item.status"
              @change="
                (value) =>
                  onChangeElementStatus(value, item, index)
              "
              :disabled="isDetail"
            >
              <el-radio label="办理中">办理中</el-radio>
              <el-radio label="已完成">已完成</el-radio>
            </el-radio-group>
          </div>
          <div
            class="item-row"
            v-show="item.status === '已完成'"
          >
            <span class="item-row-title"> 完成时间 </span>
            <!-- style="flex: 1;" -->
            <el-date-picker
              v-model="item.finishTime"
              style="width: 100%"
              type="date"
              placeholder="年/月/日"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              :disabled="isDetail"
            >
            </el-date-picker>
          </div>
          <div
            class="item-row"
            v-show="item.dictText === '其他'"
          >
            <el-input
              type="textarea"
              class="resize-textarea"
              v-model="item.remarks"
              placeholder="请输入"
              :disabled="isDetail"
            ></el-input>
          </div>
        </div>
      </div>
      <!-- <div
        class="box"
        v-for="(item, index) in resourceDictData"
        :key="index"
      >
        <div class="project-part-title">
          建设要素保障
        </div>
        <div class="checkbox">
          <el-checkbox-group v-model="constructionElements">
            <el-checkbox
              v-for="(data, i) in item.resourceDictItems"
              :key="i"
              :label="data.dictValue"
              :disabled="
                !isProjectInStorageSelected || isDetail
              "
              >{{ data.dictText }}
            </el-checkbox>
            <el-input
              v-show="isOtherChecked"
              type="textarea"
              class="resize-textarea"
              v-model="constructionElementsValue"
              placeholder="请输入"
              :disabled="isDetail"
            ></el-input>
          </el-checkbox-group>
        </div>
      </div> -->
    </div>
  </div>
</template>
<script>
import {
  getTemplateInfo,
  getElementInfo,
  getDictInfo
} from '@/api/dataManagement'
import dayjs from 'dayjs'

export default {
  name: 'project',
  props: {
    currentTab: Number,
    isDetail: Boolean,
    detailInfo: Object,
    isEdit: Boolean
  },
  data() {
    return {
      fundBuildSource: '其他',
      landingMethod: '',
      templateInfo: [],
      elementInfo: [], // 元素列表
      isNewTemplate: false,
      resourceDictData: [],
      constructionElements: [],
      constructionElementsValue: '',
      lastIndexOfSelected: 0,
      isProjectDataChanged: false
    }
  },

  watch: {
    detailInfo(newVal) {
      if (newVal?.baseMess?.pkid) {
        this.fundBuildSource =
          newVal.baseMess.fundBuildSource
        if (
          ['政府投资', '其他'].includes(
            this.fundBuildSource
          )
        ) {
          this.landingMethod = ''
        } else {
          this.landingMethod = newVal.baseMess.landingMethod
        }
        setTimeout(() => {
          const nodes = newVal.processNodeRels?.length
            ? newVal.processNodeRels
            : newVal.processNodes
          this.isNewTemplate =
            !newVal.processNodeRels?.length
          this.formatTemplateList(nodes)
          if (
            newVal.enterpriseInvestmentRels &&
            newVal.enterpriseInvestmentRels.length
          ) {
            this.formatElementTemplateList(
              newVal.enterpriseInvestmentRels
            )
          } else {
            this.getDictData()
          }
          this.constructionElements =
            newVal.baseMess.constructionElements.split(',')
          this.constructionElementsValue =
            newVal.baseMess.constructionElementsValue

          // TODO
          // this.getDictData()
        }, 30)
      }
    }
  },
  // created() {
  //   if (!this.isEdit) {
  //     this.getTemplate()
  //     this.getDictData()
  //   }
  // },

  methods: {
    notRequiredNodeFinishTime(item) {
      // return this.fundBuildSource == '政府投资' && item.nodeName == '土地批文'
      return (
        item.processId == '1' && item.nodeName == '土地批文'
      )
    },
    onChangeElementStatus(value, item, index) {
      this.$set(
        item,
        'finishTime',
        ['已办结', '提前交地'].includes(value)
          ? dayjs().format('YYYY-MM-DD')
          : ''
      )

      this.isProjectDataChanged = true
    },

    // 进度节点变更
    onChangeNodeStatus(value, item, index) {
      this.$set(
        item,
        'nodeFinishTime',
        ['已办结', '提前交地'].includes(value)
          ? dayjs().format('YYYY-MM-DD')
          : ''
      )

      setTimeout(() => {
        const isGoNext = [
          '已办结',
          '提前交地',
          '容缺补办',
          '无需办理'
        ].includes(value)
        const nextNode = this.templateInfo[index + 1]
        if (
          isGoNext &&
          nextNode &&
          (!nextNode.status || nextNode.status === '办理中')
        ) {
          this.$set(nextNode, 'selected', '1')
          this.$set(nextNode, 'nodeStatus', '办理中')
        }

        this.isProjectDataChanged = true
      }, 0)
    },

    handleCheckboxChange(data, index) {
      if (!data.selected || data.selected == '0') {
        // 如果取消勾选，清空相关字段
        this.$set(data, 'selected', '0')
        this.$set(data, 'nodeStatus', '')
        this.$set(data, 'nodeRemarks', '')
        this.$set(data, 'nodeFinishTime', '')
        this.$set(data, 'createTime', '')
        this.$set(data, 'updateTime', '')
        this.$set(data, 'updateUser', '')
        this.$set(data, 'createUser', '')
      } else {
        this.$set(data, 'selected', '1')
        this.$set(data, 'nodeStatus', '办理中')
      }

      this.isProjectDataChanged = true
    },

    // 建设要素
    onChangeCheckboxElement(data, index) {
      if (!data.selected || data.selected == '0') {
        // 如果取消勾选，清空相关字段
        if (data.dictText == '其他') {
          this.$set(data, 'remarks', '')
        }
        this.$set(data, 'status', '')
        this.$set(data, 'finishTime', '')
        this.$set(data, 'selected', '0')
      } else {
        this.$set(data, 'selected', '1')
        this.$set(data, 'status', '办理中')
      }

      this.isProjectDataChanged = true
    },

    canCheck(item, currentIndex, list) {
      // if (
      //   item.createTime &&
      //   currentIndex != this.lastIndexOfSelected
      // )
      //   return false

      const nextItem = list[currentIndex + 1]
      if (currentIndex === 0) {
        // 第一个节点始终可以勾选
        return (
          nextItem?.selected != '1' ||
          item.nodeStatus == '容缺补办'
        )
      } else {
        // 后续节点必须上一节点 nodeStatus 存在
        const prevItem = list[currentIndex - 1]
        return (
          prevItem.selected == '1' &&
          prevItem.nodeStatus &&
          prevItem.nodeStatus !== '办理中' &&
          nextItem?.selected != '1'
        )
      }
    },

    canStatusChange(item, currentIndex, list) {
      if (
        item.nodeStatus == '容缺补办' ||
        item.nodeStatus == '办理中'
      )
        return true

      // if (
      //   item.createTime &&
      //   ['已办结', '无需办理'].includes(item.nodeStatus)
      // )
      // if (
      //   item.createTime &&
      //   currentIndex != this.lastIndexOfSelected
      // )
      //   return false

      const nextItem = list[currentIndex + 1]
      if (currentIndex === 0) {
        console.log('on status change : ', item)
        return nextItem?.selected != '1'
      } else {
        // 后续节点必须上一节点 nodeStatus 存在
        const prevItem = list[currentIndex - 1]
        return (
          item.selected == '1' &&
          prevItem.selected == '1' &&
          prevItem.nodeStatus &&
          nextItem?.selected != '1'
          // && !item.updateTime
        )
      }
    },

    shouldShowContent(item, currentIndex, list) {
      // 第一个节点(i === 0)，只要 selected 为 1 就展示
      if (currentIndex === 0) {
        return list[currentIndex]?.selected == '1'
      }
      // 其他节点(i >= 1)，需要上一项的 nodeStatus 存在
      const prevItem = list[currentIndex - 1]

      return (
        (item.selected == '1' &&
          prevItem.selected == '1' &&
          prevItem.nodeStatus) ||
        item.nodeStatus
      )
    },

    // 初始化信息
    initData({ fundBuildSource, landingMethod }) {
      const prevFundBuildSource = this.fundBuildSource
      const prevLandingMethod = this.landingMethod
      console.log('init ', fundBuildSource, landingMethod)
      // 资金来源
      this.fundBuildSource = fundBuildSource || ''
      // 拿地方式
      if (
        ['政府投资', '其他', ''].includes(
          this.fundBuildSource
        )
      ) {
        this.landingMethod = ''
      } else {
        this.landingMethod = landingMethod
      }
      // if (!this.isEdit) {
      //   this.getTemplate()
      // }
      // const { fundBuildSource: oriFundBuildSource, landingMethod: oriLandingMethod } = this.detailInfo?.baseMess ?? {}
      // console.log('detailInfo baseMess', oriFundBuildSource, oriLandingMethod)
      // if (
      //   !oriFundBuildSource
      //   || (oriFundBuildSource && (oriFundBuildSource != fundBuildSource || oriLandingMethod != landingMethod))
      // ) {
      //   this.getTemplate()
      // }
      this.isNewTemplate =
        !prevFundBuildSource ||
        (prevFundBuildSource &&
          (prevFundBuildSource != this.fundBuildSource ||
            prevLandingMethod != this.landingMethod))
      if (this.isNewTemplate) {
        this.getTemplate()
        this.getDictData()
      }

      console.log(
        'this.isNewTemplate: ',
        this.isNewTemplate
      )
    },

    formatTemplateList(list) {
      let preNodeType = ''
      const arr = list.map((newItem, index) => {
        // 如果是新增状态，并且 item 中有 pkid 字段
        if (this.isNewTemplate && 'pkid' in newItem) {
          newItem.processNodeId = newItem.pkid
          newItem.pkid = ''
          newItem.createTime = ''
          newItem.updateTime = ''
          newItem.updateUser = ''
          if (index == 0) {
            newItem.selected = '1'
            newItem.nodeStatus = '办理中'
          }
        }
        newItem.showType =
          newItem.nodeType === preNodeType ? false : true
        preNodeType = newItem.nodeType

        return newItem
      })

      this.lastIndexOfSelected = Math.max(
        arr.filter((e) => e.selected == 1).length - 1,
        0
      )

      this.$set(this, 'templateInfo', arr)
    },
    formatElementTemplateList(list, isNew) {
      const arr = list.map((item, index) => {
        // 如果是新增状态，并且 item 中有 pkid 字段
        // if (!this.isEdit && 'pkid' in item) {
        if (
          (this.isNewTemplate || isNew) &&
          'pkid' in item
        ) {
          item.pkid = ''
          item.createTime = ''
          item.updateTime = ''
          item.updateUser = ''

          if (index == 0) {
            item.selected = '1'
            item.status = '办理中'
          }
        }

        return item
      })

      this.$set(this, 'elementInfo', arr)
    },

    // 获取模板信息
    getTemplate() {
      getTemplateInfo({
        fundBuildSource: this.fundBuildSource,
        landingMethod: this.landingMethod
      }).then((res) => {
        this.formatTemplateList(res.data)
      })
    },

    // 获取要素列表
    getDictData() {
      getElementInfo({
        fundBuildSource: this.fundBuildSource,
        landingMethod: this.landingMethod
      })
        .then((res) => {
          // this.resourceDictData = res.data
          this.formatElementTemplateList(
            res.data[0].resourceDictItems,
            true
          )
        })
        .catch((e) => {
          console.error('e', e)
        })
    },

    // 获取字典信息
    getDictData_old() {
      let dictCode = ''
      if (
        this.fundBuildSource == '政府投资' ||
        this.fundBuildSource == '其他'
      ) {
        dictCode = 'project_construction_elements'
      } else if (
        this.fundBuildSource == '企业投资' &&
        this.landingMethod == '拿地'
      ) {
        dictCode = 'project_enterprise_investment_nd'
      } else if (
        this.fundBuildSource == '企业投资' &&
        this.landingMethod == '入驻载体'
      ) {
        dictCode = 'project_enterprise_investment_rzzt'
      } else if (
        this.fundBuildSource == '平台公司自筹' &&
        this.landingMethod == '拿地'
      ) {
        dictCode = 'project_platform_company_nd'
      } else if (
        this.fundBuildSource == '平台公司自筹' &&
        this.landingMethod == '入驻载体'
      ) {
        dictCode = 'project_enterprise_investment_rzzt'
      }
      getDictInfo(dictCode).then((res) => {
        this.resourceDictData = res.data
      })
    }
  }
}
</script>
<style scoped lang="scss">
.project {
  width: 100%;
  padding: 20px 20px 0 20px;
  display: flex;
  box-sizing: border-box;
  font-size: 16px;

  font-weight: 500;
  color: #4c565c;

  > .left {
    width: 70%;
    // margin: 10px 0;
    font-size: 16px;

    .item-tit {
      font-size: 14px;
      margin-bottom: 10px;
    }
    .item-radio-group {
      display: flex;
      flex-direction: column;
      gap: 5px;
    }
  }

  > .right {
    flex: 1;
    padding-left: 10px;
    padding-top: 20px;
    > .project-part-title {
      font-size: 16px;
      color: #4c565c;
      margin-bottom: 24px;
      position: relative;
      line-height: 16px;
      padding-left: 11px;

      &::after {
        background: linear-gradient(
          180deg,
          #40ebff,
          #bcf8ff
        );
        position: absolute;
        content: '';
        width: 4px;
        height: 16px;
        top: 0;
        left: 0;
      }
    }
  }
  .form {
    width: 100%;
    margin-bottom: 10px;

    > .title {
      position: relative;
      margin-top: 20px;
      margin-bottom: 10px;
      line-height: 16px;

      &::after {
        content: '';
        width: 4px;
        height: 16px;
        background: linear-gradient(
          180deg,
          #40ebff,
          #bcf8ff
        );
        position: absolute;
        left: -10px;
        top: 0;
      }
    }

    // > .item {
    //   font-size: 14px;
    //   margin-bottom: 30px;

    > .item-title {
      display: flex;
      align-items: center;
      margin-bottom: 10px;

      > .name {
        margin-left: 8px;
        font-size: 14px;

        &.active {
          color: #bec3cf;
        }

        > span {
          margin-left: 10px;
          color: #bec3cf;
          font-size: 14px;
        }
      }
    }

    > .content {
      padding-left: 20px;
      box-sizing: border-box;

      .item-row {
        display: flex;
        align-items: center;
        margin-bottom: 8px;
      }

      .item-row-title {
        display: inline-flex;
        width: 5em;
        flex: 0 0 5em;
      }

      .el-col {
        // padding-right: 20px;
        box-sizing: border-box;

        &:last-child {
          padding-right: 0;
        }
      }
    }
    // }
  }
}

:deep().el-textarea__inner {
  font-size: 14px;
  font-family: PingFang SC;
  font-weight: 400;
  max-width: 320px !important;
}

.checkbox {
  :deep().el-checkbox {
    width: 100%;
    margin-bottom: 10px;
  }
}

:deep(.el-input__inner) {
  max-width: 320px !important;
  height: 32px !important;
}

:deep(.el-input__icon) {
  line-height: 32px !important;
}
</style>
